package com.crm.utils;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;


@Component
public class BackupTask {

    @Value("${spring.datasource.username}")
    private String userName;
    //    @Value("${druid.password}")
    @Value("${spring.datasource.password}")
    private String password;

    private DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHH");

    private static final String BACKUP_PATH = "/home/tomcat/backup/";
    private static final int EXPIRED_MONTH = -3;

    @Scheduled(cron = "0 0 0 * * ?")//每晚0点备份数据库一次
    public void task() {

        String gzFileName = BACKUP_PATH + dateFormat.format(new Date()) + ".tar.gz";
        File file = new File(gzFileName);

        if (backup(userName, password, gzFileName)) {
            System.out.println(dateFormat.format(new Date()) + "===成功备份数据库===");

            deleteExpiredFile();
        } else {
            System.out.println(dateFormat.format(new Date()) + "===备份数据库失败===");
        }

    }

    private void deleteExpiredFile() {
        File backupFile = new File(BACKUP_PATH);
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, EXPIRED_MONTH);
        long expiredTime = calendar.getTimeInMillis();
        File[] fileList = backupFile.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {

                if (pathname.getName().endsWith(".tar.gz")
                        && pathname.lastModified() < expiredTime) {
                    return true;
                } else {
                    return false;
                }
            }
        });
        for (File file : fileList) {
            System.out.println("删除过期备份："+file.getName());
            file.delete();
        }
    }

    private boolean backup(String userName, String password, String gzFileName) {
        String bakFileName = BACKUP_PATH + "crmVue.sql";
        if (exportDatabase(userName, password, bakFileName)) {
            try {
                Process process = Runtime.getRuntime().exec("tar -cvzf " + gzFileName + " " + bakFileName);
                if (process.waitFor() == 0) {
                    File file = new File(bakFileName);
                    if (file.exists()) file.delete();
                    return true;
                }
            } catch (IOException | InterruptedException e) {
                e.printStackTrace();
            }
            return false;
        } else {
            return false;
        }

    }


    private boolean exportDatabase(String userName, String password, String bakFileName) {

        PrintWriter printWriter = null;
        BufferedReader bufferedReader = null;
        try {
            printWriter = new PrintWriter(new OutputStreamWriter(new FileOutputStream(bakFileName), "utf8"));

            Process process = Runtime.getRuntime().exec(" mysqldump -h 127.0.0.1" + " -u" + userName + " -p" + password + " --set-charset=UTF8 fcwrdb");
            InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                printWriter.println(line);
            }
            printWriter.flush();
            if (process.waitFor() == 0) {//0 表示线程正常终止。

                return true;
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
                if (printWriter != null) {
                    printWriter.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return false;
    }
}
